﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WucCloud.Database
{
    public class UnitOfWork :IUnitOfWork, IDisposable
    {
        private readonly ISqlSugarClient _sqlSugarClient;
        private readonly ITenant _tenant;

        public UnitOfWork(ISqlSugarClient sqlSugarClient)
        {
            _sqlSugarClient = sqlSugarClient;
            _tenant = _sqlSugarClient as ITenant;
        }

        /// <summary>
        /// 获取DB，保证唯一性
        /// </summary>
        /// <returns></returns>
        public SqlSugarClient GetDbClient()
        {
            // 必须要as，后边会用到切换数据库操作
            return _sqlSugarClient as SqlSugarClient;
        }

        /// <summary>
        /// 开启事务
        /// </summary>
        public void BeginTran()
        {
            _tenant.BeginTran();
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        public void CommitTran()
        {
            try
            {
                _tenant.CommitTran();
            }
            catch (Exception ex)
            {
                _tenant.RollbackTran();
                //Logger.Error($"{ex.Message}\r\n{ex.InnerException}");
            }
        }

        /// <summary>
        /// 回滚事务
        /// </summary>
        public void RollbackTran()
        {
            _tenant.RollbackTran();
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        public void Dispose()
        {
            GetDbClient().Dispose();
        }
    }
}
